package com.cypher.encryptionanddecryption.util;

import java.security.NoSuchAlgorithmException;

import javax.crypto.Cipher;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;

public class AESUtils {
    /**
     * AES加密
     * @param key   密钥
     * @param data  需要加密的数据
     * @return
     */
    public static String encrypt(String key, String data) {
        try {
            byte[] keys = HexUtils.hexToBytes(key);
            data = data.replace(" ", "");
            byte[] datas = HexUtils.hexToBytes(data);
            SecretKeySpec sKeySpec = new SecretKeySpec(keys, "AES");
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS7Padding");
            cipher.init(Cipher.ENCRYPT_MODE, sKeySpec);
            byte[] results = cipher.doFinal(datas);
            return HexUtils.bytesToHex(results);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * AES解密
     * @param key 密钥
     * @param data 解密数据
     * @return
     */
    public static String decrypt(String key, String data) {
        try {
            byte[] keys = HexUtils.hexToBytes(key);
            data = data.replace(" ", "");
            byte[] datas = HexUtils.hexToBytes(data);

            SecretKeySpec sKeySpec = new SecretKeySpec(keys, "AES");
            Cipher cipher = Cipher.getInstance("AES/ECB/NoPadding");
            cipher.init(Cipher.DECRYPT_MODE, sKeySpec);
            byte[] decryptData = cipher.doFinal(datas);
            return HexUtils.bytesToHex(decryptData);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }


    /**
     * 生成 HMACSHA256
     * @param data 待处理数据
     * @param key 密钥
     * @return 加密结果
     * @throws Exception
     */
    public static String HMACSHA256(String key, String data) throws Exception {
        Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
        byte[] keys = HexUtils.hexToBytes(key);
        SecretKeySpec secret_key = new SecretKeySpec(keys, "HmacSHA256");
        sha256_HMAC.init(secret_key);
        byte[] datas = HexUtils.hexToBytes(data);
        byte[] result = sha256_HMAC.doFinal(datas);
        return HexUtils.bytesToHex(result);
    }
}
